<template>
  <div>
<!--    导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card >
<!--      搜索区域-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容"
          v-model="paramsInfo.query"
          clearable
          @clear="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

<!--      表格-->
      <el-table
        :data="usersList"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index"  label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
<!--          作用域卡槽-->
          <template slot-scope="scope">
            <el-switch @change="updateUserStatus(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="190px">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="editUserShow(scope.row.id)" icon="el-icon-edit"></el-button>
            <el-button type="danger" size="mini" @click="deleteUser(scope.row.id)" icon="el-icon-delete"></el-button>
            <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

<!--      分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paramsInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="paramsInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--  添加用户-->
    <el-dialog title="添加用户"
               :visible.sync="addDialogVisible"
               @close="handleClose"
               width="30%">
      <span>
        <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addFrom.username"></el-input>
          </el-form-item>
           <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addFrom.password"></el-input>
          </el-form-item>
           <el-form-item label="邮箱" prop="email">
            <el-input v-model="addFrom.email"></el-input>
          </el-form-item>
           <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
    </el-dialog>


<!--    修改弹出-->
    <el-dialog
      title="修改"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editHandleClose">
      <span>
        <el-form :model="editFrom" :rules="addFromRules" ref="editFromRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editFrom.username" disabled></el-input>
          </el-form-item>
           <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFrom.email"></el-input>
          </el-form-item>
           <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
      <el-button @click="editDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="updateUserInfo">确 定</el-button>
    </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Users",
  data: function () {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (regEmail.test(value)){
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule, value, cb) => {
      if((/^1[3456789]\d{9}$/.test(value))){
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      paramsInfo: {
        'query': '',
        'pagenum': 1,
        'pagesize': 10,
      },
      usersList: [],  // 用户数据
      total: 0,
      addDialogVisible: false,  // 添加用户弹出层默认关闭
      editDialogVisible: false, // // 修改用户弹出层默认关闭
      addFrom: { // 添加用户数据
        username: '',
        password: '',
        email: '',
        mobile: '',
      },

      editFrom:{ // 修改用户数据
        id: 0,
        username:'',
        email:'',
        mobile:'',
      },
      addFromRules: { // 验证数据
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '用户名长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入电话', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ],
      },
      editFromRules:{ // 修改数据验证

      }
    }
  },
  created() {
    this.getUserList(this.paramsInfo.pagenum)
  },
  methods:{
    async getUserList(){
     const {data: res} = await this.$http.get('users',{params:this.paramsInfo})
     if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.usersList = res.data.users
      this.total = res.data.total
    },

    // 监听pagesSize 改变的事件
    handleSizeChange(newSize){
      this.paramsInfo.pagesize = newSize
      this.getUserList()
    },

    // 监听页面值改变
    handleCurrentChange(page){
      this.paramsInfo.pagenum = page
      this.getUserList()
    },

    // 更改用户状态
    async updateUserStatus(user){
      const {data: res} = await this.$http.put(`users/${user.id}/state/${user.mg_state}`);
      if (res.meta.status !== 200) {
        user.mg_state = !user.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success(res.meta.msg)
    },

    // 添加用户
    async addUser(){
      this.$refs.addFromRef.validate(async valid=>{
        if (!valid) return
        const {data :res} = await this.$http.post('users',this.addFrom);
        if(res.meta.status !== 201){
          return this.$message.error(res.meta.msg)
        }

        this.addDialogVisible = false
        await this.getUserList()
        return this.$message.success(res.meta.msg)
      })
    },

    // 关闭添加用户框回调
    handleClose(){
      this.$refs.addFromRef.resetFields();
    },

    // 关闭修改用户框回调
    editHandleClose(){
      this.$refs.editFromRef.resetFields();
    },

    // 删除用户
    async deleteUser(id){
      this.$confirm('是否永久删除此用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then( async () => {
        const {data: res } = await this.$http.delete(`users/${id}`)
        if (res.meta.status !== 200){
           return  this.$message({
              type: 'info',
              message: res.meta.msg
            });
        }
       this.$message({
          type: 'success',
          message:'删除成功'
        });
        await this.getUserList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 显示修改用户弹出层
    async editUserShow(id){
      this.editDialogVisible = true
      // 获取用户数据
      const {data: res} = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200){
        this.editDialogVisible = false
        return this.$message.error("获取用户信息失败")
      }
      this.editFrom = res.data
    },
    // 修改用户
    async updateUserInfo(){
      this.$refs.editFromRef.validate(async valid =>{
        if (!valid) return
        const {data: res} = await this.$http.put(`users/${this.editFrom.id}`,this.editFrom)
        if(res.meta.status !== 200){
          this.editDialogVisible = false
          return this.$message.error("用户更新失败")
        }
        this.$message.success("用户更新成功")
        this.editDialogVisible = false

        await this.getUserList()
      })

    }
  }
}
</script>

<style lang="less" scoped>
.el-popconfirm{
  background-color: #fff;
}
</style>
